package com.zego.wawaji.ui.base;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.umeng.analytics.MobclickAgent;
import com.zego.wawaji.R;
import com.zego.wawaji.base.utils.InputUtils;

/**
 * 继承AppCompatActivity, 后续新创建Activity需要继承改Base
 * <p>
 * Created by Su on 2017/9/29.
 */
public class BaseAppCompatActivity extends AppCompatActivity {
    protected ImmersionBar mImmersionBar;  // 沉浸式管理
    private boolean canBack = true;   //是否能右滑退出
    private RightSlidLinearLayout linearLayout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (isImmersionBar())
            initImmersionBar();
        if (canBack) {
            initSlideBack();
        }
    }

    /**
     * 设置当前页面是否支持滑动退出，需要写在继承该类的子类onCreate中super.onCreate();的前面
     *
     * @param canBack 能否支持右滑退出
     */
    public void isCanBack(boolean canBack) {
        this.canBack = canBack;
    }

    /**
     * 右滑返回：添加忽略view，内部维护一个list，可在一个页面添加多个忽略view
     */
    public void addIgnoredView(View v) {
        if (linearLayout != null) linearLayout.addIgnoredView(v);
    }

    /**
     * 顶层触摸控制
     */
    private void initSlideBack() {
        linearLayout = (RightSlidLinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_slideback_container, null);
        linearLayout.attachToActivity(this);
    }


    /**
     * Dialog样式Act需屏蔽
     */
    protected boolean isImmersionBar() {
        return true;
    }

    /**
     * 初始化沉浸式
     */
    protected void initImmersionBar() {
        try {
            mImmersionBar = ImmersionBar.with(this);
            mImmersionBar.keyboardEnable(true)
                    .init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 为标题栏预留出状态栏空间
     */
    private void setImmerseLayout() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                View view = findViewById(R.id.base_title_bg);
//                view.setPadding(0, App.statusBarHeight, 0, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        setImmerseLayout();
        getWindow().setBackgroundDrawableResource(R.color.transparent);  // 去除Theme设置的默认背景，减少绘图层级
    }

    @Override
    public void finish() {
        super.finish();
        //关闭键盘
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mImmersionBar != null)
            mImmersionBar.destroy();  //销毁防止内存溢出
    }

    /**
     * 设置返回组件
     */
    public void setBackView() {
        ImageView back = (ImageView) this.findViewById(R.id.base_back);
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 设置标题
     */
    public void setTitle(String txt) {
        TextView textView = (TextView) this.findViewById(R.id.base_title_title);
        textView.setVisibility(View.VISIBLE);
        textView.setText(txt);
    }

    /**
     * 设置标题右侧文字
     */
    public void setTitleRight(String txt, View.OnClickListener listener) {
        TextView textView = (TextView) findViewById(R.id.base_title_right);
        textView.setVisibility(View.VISIBLE);
        textView.setOnClickListener(listener);
        textView.setText(txt);
    }

    /**
     * 设置标题左侧图片
     */
    public ImageView setTitleLeftImg(int res, View.OnClickListener listener) {
        ImageView iv = (ImageView) this.findViewById(R.id.base_left_img);
        ImageView back = (ImageView) this.findViewById(R.id.base_back);
        iv.setBackgroundResource(res);
        iv.setVisibility(View.VISIBLE);
        back.setVisibility(View.GONE);
        iv.setOnClickListener(listener);
        return iv;
    }

    /**
     * 设置标题右侧图片
     */
    public ImageView setTitleRightImg(int res, View.OnClickListener listener) {
        ImageView iv = (ImageView) this.findViewById(R.id.base_title_right_img);
        iv.setBackgroundResource(res);
        iv.setVisibility(View.VISIBLE);
        iv.setOnClickListener(listener);
        return iv;
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    // =================== EditText与软键盘交互 Start =================================
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isTouchView(filterViewByIds(), ev)) return super.dispatchTouchEvent(ev);
            if (hideSoftByEditViewIds() == null || hideSoftByEditViewIds().length == 0)
                return super.dispatchTouchEvent(ev);
            View v = getCurrentFocus();
            if (isFocusEditText(v, hideSoftByEditViewIds())) {
                if (isTouchView(hideSoftByEditViewIds(), ev))
                    return super.dispatchTouchEvent(ev);
                //隐藏键盘
                InputUtils.hideInputForce(this);
                clearViewFocus(v, hideSoftByEditViewIds());

            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 传入EditText的Id
     * 没有传入的EditText不做处理
     *
     * @return id 数组
     */
    public int[] hideSoftByEditViewIds() {
        return null;
    }

    /**
     * 传入要过滤的View
     * 过滤之后点击将不会有隐藏软键盘的操作
     *
     * @return id 数组
     */
    public View[] filterViewByIds() {
        return null;
    }

    /**
     * 清除editText的焦点
     *
     * @param v   焦点所在View
     * @param ids 输入框
     */
    public void clearViewFocus(View v, int... ids) {
        if (null != v && null != ids && ids.length > 0) {
            for (int id : ids) {
                if (v.getId() == id) {
                    v.clearFocus();
                    break;
                }
            }
        }
    }

    /**
     * 隐藏键盘
     *
     * @param v   焦点所在View
     * @param ids 输入框
     * @return true代表焦点在edit上
     */
    public boolean isFocusEditText(View v, int... ids) {
        if (v instanceof EditText) {
            EditText tmp_et = (EditText) v;
            for (int id : ids) {
                if (tmp_et.getId() == id) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 是否触摸在指定view上面,对某个控件过滤
     */
    public boolean isTouchView(View[] views, MotionEvent ev) {
        if (views == null || views.length == 0) return false;
        int[] location = new int[2];
        for (View view : views) {
            view.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];
            if (ev.getX() > x && ev.getX() < (x + view.getWidth())
                    && ev.getY() > y && ev.getY() < (y + view.getHeight())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否触摸在指定view上面,对某个控件过滤
     */
    public boolean isTouchView(int[] ids, MotionEvent ev) {
        int[] location = new int[2];
        for (int id : ids) {
            View view = findViewById(id);
            if (view == null) continue;
            view.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];
            if (ev.getX() > x && ev.getX() < (x + view.getWidth())
                    && ev.getY() > y && ev.getY() < (y + view.getHeight())) {
                return true;
            }
        }
        return false;
    }
    // =================== EditText与软键盘交互 End =================================
}
